#include "widget.h"
#include<QPaintEvent>
#include<QPainter>//绘图
#include<QPixmap>//图片
#include<QCursor>
#include<QMetaEnum>

Widget::Widget(QWidget *parent)
    : QWidget(parent),
    timer(new QTimer(this)),
    menu(new QMenu(this))
{
    this->setWindowFlag(Qt::FramelessWindowHint);//去除窗口边框
    this->setAttribute(Qt::WA_TranslucentBackground);//背景透明

    this->installEventFilter(new DragFilter);

    connect(timer,&QTimer::timeout,[this](){
        static int index=0;//记录显示图片的当前动作索引
        auto paths = this->action_map.value(this->cur_role_act);
        this->cur_role_pix=paths[index++%paths.size()];

        this->update();

    });

    initMenu();

    loadRoleActRes();

    showActAnimation(RoleAct::SmallCat);
}

Widget::~Widget() {}

void Widget::showActAnimation(RoleAct k)
{
    timer->stop();

    this->cur_role_act=k;

    timer->start(225);
}

void Widget::onMenuTriggered(QAction *action)
{
    QMetaEnum me=QMetaEnum::fromType<RoleAct>();

    bool ok;
    int k = me.keyToValue(action->text().toStdString().c_str(),&ok);
    if(!ok)
        return;

    showActAnimation(static_cast<RoleAct>(k));
    }

void Widget::paintEvent(QPaintEvent *envent)
{

    QPainter painter(this);

    painter.scale(0.2, 0.2);

    QPixmap pix;
    pix.load(this->cur_role_pix.toLocalFile());

    painter.drawPixmap(0,0,pix);

}

void Widget::contextMenuEvent(QContextMenuEvent *event)
{
    this->menu->popup(QCursor::pos());
}

void Widget::loadRoleActRes()
{
    auto addRes=[this](RoleAct k,QString path,int count)
    {
        QList<QUrl> paths;
        char buf[260];
        for(int i=0;i<count;++i) {
            memset(buf,0,sizeof(buf));
            sprintf_s(buf,path.toStdString().c_str(),i);
            paths.append(QUrl::fromLocalFile(buf));
        }
        action_map.insert(k,paths);
    };

    addRes(RoleAct::BigCat,":/BigCat/猫/大猫/%d.png",5);
    addRes(RoleAct::SmallCat,":/SmallCat/猫/小猫/%d.png",6);
}

void Widget::initMenu()
{
    menu->addAction("SmallCat");
    menu->addAction("BigCat");

    QAction* act=new QAction("Hide");
    connect(act,&QAction::triggered,[this](){
        this->setVisible(false);
    });

    menu->addAction(act);

    connect(this->menu,&QMenu::triggered,this,&Widget::onMenuTriggered);
}
